"use strict";
// NG2
import {
  Inject,
  Component,
  NgModule,
	Injectable
} from '@angular/core';
// redux
import {
  createStore,
  Store,
  compose,
  StoreEnhancer
} from 'redux';
// action
import { UserActions } from './actions';
// reducer
import {
  AppState,
  getAction,
  default as reducer
} from './reducers';

import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppStore } from './store';

// root component
@Component({
  selector: 'app',
  template: `
  <div>
    {{app}}
  </div>
  <button (click)="save()">点击</button>
  `
})
class App {
  app: any;
  constructor(@Inject(AppStore) private store: Store<AppState>) {
    // 获取状态机
    let state = this.store.getState();
    this.app = getAction(state);
    // 监听store
    store.subscribe(() => {
     // 获取状态机
     state = this.store.getState();
     // 查看store数据
     this.app = getAction(state);
    });
  }
  save(){
    // 修改store数据
    this.store.dispatch(UserActions.addThread());
  }
}

// 时光机
let devtools: StoreEnhancer<AppState> =
  window['devToolsExtension'] ?
  window['devToolsExtension']() : f => f;

// 创建store
let store: Store<AppState> = createStore<AppState>(
  reducer,
  compose(devtools)
);

@NgModule({
  declarations: [
    App
  ],
  imports: [
    BrowserModule
  ],
  bootstrap: [ App ],
	providers: [
    // 非类依赖
    { 
      provide: AppStore,
      useFactory: () => store 
    }
	]
})
class Module {}

platformBrowserDynamic().bootstrapModule(Module)
  .catch(err => console.error(err));